package com.sinopec.basemodule.launchcontract

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContract
import com.sinopec.basemodule.utils.kotlin.navigationClass

/**
 * create by lwj at 2023/4/12
 *
 *
 * 一个轮子
 * 设置值获取值 契约
 *
 */
open class SetAndGetValueResultContract<Req, Res>(
    private val req: Request<Req>,
    private val res: Response<Res>,
    private val targetPathClass: Class<*>
) : ActivityResultContract<Req, Res>() {

    interface Request<T> {
        fun getParams(activity: Activity): T?
        fun createIntent(intent: Intent, t: T?)

        companion object {
            fun <T> from(create: GetSetFromIntent<T>): Request<T> {
                return object : Request<T> {
                    override fun getParams(activity: Activity): T? {
                        return create.get(activity.intent)
                    }

                    override fun createIntent(intent: Intent, t: T?) {
                        return create.set(t, intent)
                    }
                }
            }
        }
    }

    interface Response<T> {
        fun setResult(activity: Activity, result: T?)
        fun parseResult(resultCode: Int, intent: Intent?): T?

        companion object {
            fun <T> from(create: GetSetFromIntent<T>): Response<T> {
                return object : Response<T> {
                    override fun setResult(activity: Activity, result: T?) {
                        activity.setResult(Activity.RESULT_OK, Intent().also {
                            create.set(result, it)
                        })
                    }

                    override fun parseResult(resultCode: Int, intent: Intent?): T? {
                        return create.get(intent)
                    }
                }
            }
        }

    }

    fun getParams(activity: Activity): Req? {
        return req.getParams(activity)
    }

    override fun createIntent(context: Context, input: Req?): Intent {
        return Intent(
            context,
            targetPathClass
        ).also {
            req.createIntent(it, input)
        }
    }

    override fun parseResult(resultCode: Int, intent: Intent?): Res? {
        return res.parseResult(resultCode, intent)
    }

    fun setResult(activity: Activity, result: Res) {
        res.setResult(activity, result)
    }

}


/**
 * create by lwj at 2023/4/25
 * 简便方法
 */
fun <Req, Res> String.setAndGetValueResultContract(
    req: GetSetFromIntent<Req>,
    res: GetSetFromIntent<Res>,
) :SetAndGetValueResultContract<Req, Res>{
    return SetAndGetValueResultContract<Req, Res>(
        SetAndGetValueResultContract.Request.from(req),
        SetAndGetValueResultContract.Response.from(res),
        this.navigationClass
    )
}